package com.zhsj.OkeHomeConsumption.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.widget.SettingBar;
import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.RestaurantBean;
import com.zhsj.OkeHomeConsumption.ui.activity.mvp.ResraurantUIInterface;
import com.zhsj.OkeHomeConsumption.ui.activity.mvp.RestaurantPresenter;
import com.zhsj.OkeHomeConsumption.utils.GoActivityUtils;
import com.zhsj.OkeHomeConsumption.utils.JsonUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

/**
 * 商铺详情页面
 */
public class RestaurantActivity extends MyActivity implements ResraurantUIInterface, View.OnClickListener {

    @BindView(R.id.text1)
    TextView text1;
    @BindView(R.id.text2)
    TextView text2;
    @BindView(R.id.map_lin)
    LinearLayout mapLin;
    @BindView(R.id.phone_lin)
    LinearLayout phoneLin;
    @BindView(R.id.lin)
    LinearLayout lin;
    private TextView shop_headname;
    private RecyclerView list_photo;
    private RecyclerView info_list;
    private ImageView enter, banner_image;
    private ArrayList<RestaurantBean> photolist;
    private ArrayList<RestaurantBean> infolist;
    private ResturnAdapter resturnAdapter;
    private RestaurantPresenter restaurantPresenter;
    private ItemResturnAdapter photoadapter;
    private int itemid;
    private RestaurantBean restaurantBean = null;


    @Override
    protected int getLayoutId() {
        return R.layout.item;
    }

    @Override
    protected int getTitleId() {
        return 0;
    }

    protected void initView() {
        restaurantPresenter = new RestaurantPresenter(getActivity(), this);
        shop_headname = (TextView) findViewById(R.id.shop_headname);
        list_photo = (RecyclerView) findViewById(R.id.list_photo);
        enter = (ImageView) findViewById(R.id.enter);
        banner_image = (ImageView) findViewById(R.id.banner_image);
        banner_image.setOnClickListener(this);
        info_list = (RecyclerView) findViewById(R.id.info_list);

        photolist = new ArrayList<>();
        infolist = new ArrayList<>();


        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        info_list.setLayoutManager(layoutManager);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(OrientationHelper.HORIZONTAL);
        list_photo.setLayoutManager(linearLayoutManager);
        mapLin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (restaurantBean != null) {
                    startActivity(new Intent(RestaurantActivity.this, RestaurantMapActivity.class)
                            .putExtra("bean", restaurantBean));
                }
            }
        });
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        itemid = intent.getIntExtra("itemid", 10);

        double userLongitude = Hawk.get("userLongitude");

        double userLatitude = Hawk.get("userLatitude");
        restaurantPresenter.ShopListPost(itemid, userLongitude, userLatitude);
        phoneLin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (restaurantBean.getShopMobile() != null) {
                    XXPermissions.with(getActivity())
                            .permission(Permission.CALL_PHONE) //不指定权限则自动获取清单中的危险权限
                            .request(new OnPermission() {

                                @Override
                                public void hasPermission(List<String> granted, boolean isAll) {
                                    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                                    builder.setTitle("确定呼叫商家吗？");
                                    builder.setMessage("号码:" + restaurantBean.getShopMobile());
                                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + restaurantBean.getShopMobile()));
                                            startActivity(intent);
                                        }
                                    });
                                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            dialogInterface.dismiss();
                                        }
                                    });
                                    builder.show();
                                }

                                @Override
                                public void noPermission(List<String> denied, boolean quick) {
                                }
                            });
                }

            }
        });
    }

    @Override
    public void ShopListPost(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                restaurantBean = JsonUtils.object(jsonobj.toString(), RestaurantBean.class);

                if (restaurantBean.getShopLocation() != null) {
                    text1.setText(restaurantBean.getShopLocation());
                    text2.setText(restaurantBean.getAddress());
                } else {
                    lin.setVisibility(View.GONE);
                }
                shop_headname.setText(restaurantBean.getShopName());
                infolist.add(restaurantBean);
                resturnAdapter = new ResturnAdapter();
                info_list.setAdapter(resturnAdapter);


                photolist.add(restaurantBean);
                photoadapter = new ItemResturnAdapter(restaurantBean.getShopInsidePicList());
                list_photo.setAdapter(photoadapter);


                resturnAdapter.notifyDataSetChanged();
                photoadapter.notifyDataSetChanged();
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("ShopListPost", "获取店铺详情");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) and run LayoutCreator again
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.banner_image:
                Intent intent1 = new Intent(getActivity(), WebActivity.class).putExtra("url",
                        OkeHomeConsumptionApi.ELVDOU_BASEURL_H5 + "http://www.okejia.com/app/h5/platform/30.html");
                startActivity(intent1);
                break;
        }
    }

    public class ResturnAdapter extends BaseQuickAdapter<RestaurantBean, BaseViewHolder> {

        public ResturnAdapter() {
            super(R.layout.shopinfo_item, infolist);
        }

        @Override
        protected void convert(BaseViewHolder helper, final RestaurantBean item) {
            SettingBar shopaddressitem = helper.itemView.findViewById(R.id.shopaddressitem);

            SettingBar shop_kinditem = helper.itemView.findViewById(R.id.shop_kinditem);

            SettingBar shop_nameitem = helper.itemView.findViewById(R.id.shop_nameitem);

            SettingBar shoptel_item = helper.itemView.findViewById(R.id.shoptel_item);

            SettingBar shoptime_item = helper.itemView.findViewById(R.id.shoptime_item);
            if (item != null && item.getShopName() != null && item.getCategoryText() != null)
                shopaddressitem.setRightText(item.getAddress());
            shop_kinditem.setRightText(item.getCategoryText());
            shop_nameitem.setRightText(item.getShopName());
            shoptel_item.setRightText(item.getShopMobile());
            shoptime_item.setRightText(item.getWorkTime() + "");
            if (item.getShopService() != null) {
                helper.setText(R.id.shop_serviceitem, item.getShopService());

            } else {
                helper.setText(R.id.shop_serviceitem, "暂无");
            }
        }
    }


    public class ItemResturnAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        public ItemResturnAdapter(@Nullable List<String> data) {
            super(R.layout.item_shop_recy_img, data);
        }


        @Override
        protected void convert(@NonNull BaseViewHolder helper, final String item) {
            ImageView img = helper.itemView.findViewById(R.id.image);
            Glide.with(getActivity()).load(item)
                    .error(R.drawable.zhanweitu_bg)
                    .placeholder(R.drawable.zhanweitu_bg).into(img);
            img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GoActivityUtils.GoPhotoViewpagerActivity
                            (PhotoActivity.createCircleIntent(getActivity(), Collections.singletonList(item), 0, "1")
                                    , getActivity()
                                    , v
                            );
                }
            });
        }
    }

}
